package com.a2j.web.car.service.impl;

import com.a2j.beans.base.BaseBean;
import com.a2j.beans.base.code.ResponseCode;
import com.a2j.beans.car.CarSpecification;
import com.a2j.exception.BizException;
import com.a2j.web.car.mapper.CarSpecificationMapper;
import com.a2j.web.car.service.CarSpecService;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.List;

/**
 * Author: bzb
 * Data: 2021/10/29 17:47
 * Desc: 车规
 */
@Service
public class CarSpecificationImpl implements CarSpecService {

    @Resource
    CarSpecificationMapper mapper;


    @Override
    public void deleteCarSpec(Integer id) {
        Assert.notNull(id, "车规id不能为空");

        int result = mapper.deleteCarSpec(id);
        if (result == 0) {
            throw new BizException(ResponseCode.FAILED_DELETE);
        }
    }

    @Override
    public void addCarSpec(CarSpecification record) {
        Assert.notNull(record, "车规信息不能为空");
        // 查询数据库,看哪些字段必能为空
        Assert.hasLength(record.getName(), "车规名称不能为空");

        // 新建信息,填上空缺字段
        record.setCreaterName("bzb");
        record.setId(null); // 主键置空

        int result = mapper.addCarSpec(record);
        if (result == 0) {
            throw new BizException(ResponseCode.FAILED_ADD);
        }
    }

    @Override
    public void updateCarSpec(CarSpecification record) {
        Assert.notNull(record, "车规信息不能为空");
        Assert.notNull(record.getId(), "车规id不能为空");

        int result = mapper.updateCarSpec(record);
        if (result == 0) {
            throw new BizException(ResponseCode.FAILED_UPDATE);
        }
    }

    @Override
    public void enable(Integer id, Integer enable) {
        Assert.notNull(id, "车规id不能为空");
        if (enable == null) enable = 0;

        CarSpecification carSpec = CarSpecification
                .builder()
                .id(id)
                .enable(enable)
                .build();

        int result = mapper.updateCarSpec(carSpec);
        if (result == 0) {
            throw new BizException(ResponseCode.FAILED_UPDATE);
        }
    }

    @Override
    public BaseBean<CarSpecification> getCarSpecDetail(Integer id) {
        Assert.notNull(id, "车规id不能为空");
        CarSpecification carSpecs = mapper.getCarSpecDetail(id);

        if (carSpecs == null) {
            throw new BizException(ResponseCode.NO_DATA);
        }
        return BaseBean.success(carSpecs);
    }

    @Override
    public BaseBean<List<CarSpecification>> getAllCarSpecs() {
        List<CarSpecification> carSpecs = mapper.getAllCarSpecs();

        if (carSpecs == null) {
            throw new BizException(ResponseCode.NO_DATA);
        }
        return BaseBean.success(carSpecs);
    }
}
